package com.zengqingfa.shardingjdbc.demo.sharding.range;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 *
 * @fileName: ShardingDatabaseRangeAlgorithm
 * @author: zengqf3
 * @date: 2021-3-28 21:40
 * @description: 分库算法
 */
@Slf4j
public class ShardingDatabaseRangeAlgorithm implements RangeShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
            RangeShardingValue<String> shardingValue) {
        log.info("Range database collection:" + JSON.toJSONString(availableTargetNames) + ",rangeShardingValue:" + JSON
                .toJSONString(shardingValue));
        Set<String> result = new LinkedHashSet<>();
        // between and 的起始值
        Long lower = Long.valueOf(shardingValue.getValueRange().lowerEndpoint());
        Long upper = Long.valueOf(shardingValue.getValueRange().upperEndpoint());
        // 循环范围计算分库逻辑
        for (Long i = lower; i <= upper; i++) {
            long tenant_code_mod = Math.abs(i.toString().hashCode() % 2 + 1);
            for (String databaseName : availableTargetNames) {
                if (databaseName.endsWith(String.format("%02d", tenant_code_mod))) {
                    log.info("return database:" + databaseName);
                    result.add(databaseName);
                }
            }
        }
        return result;
    }
}
